package com.dengyafei.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @author 邓亚非
 */
@Slf4j
public class JwtUtil {

    private final static String APP_SECRET = "123456";

    private final static long EXPIRE_TIME = 10000 * 60 * 1000;

    /**
     * 生成jwt token
     *
     * @param map
     * @return
     */
    public static String generateToken(Map<String, String> map) {
        String userId = map.get("userId");
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(APP_SECRET);
        String sign = null;
        try {
            sign = JWT.create().withAudience(userId).withExpiresAt(date).sign(algorithm);
            log.info("token:" + sign);
            return sign;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        log.error("token生成失败");
        return null;
    }

    /**
     * 获取用户信息
     *
     * @param token
     * @return
     */
    public static String getUserInfo(String token) {
        String userId = null;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            return userId;
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(APP_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            log.info("token认证成功:" + jwt);
            return true;
        } catch (JWTVerificationException e) {
            throw new RuntimeException("token无效,请重新获取");
        }
    }

    /**
     * 获取真实token
     *
     * @param request
     * @return
     */
    public static String getRealToken(HttpServletRequest request) {
        String hearders = request.getHeader("token");
        if (ObjectUtils.isEmpty(hearders)) {
            return "";
        }
        return hearders;
    }
}